package com.abc.wy.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;

public class AESUtil {

    public static final String AES_KEY = "1234567890abcdef";

    public static void main(String[] args) throws Exception {
        // 原文:
        String message = "123456";
        System.out.println("Message: " + message);
        // 加密:
        // byte[] data = message.getBytes(StandardCharsets.UTF_8);
        String encrypted = encrypt(message);
        System.out.println("Encrypted: " + encrypted);
        // 解密:
        String decrypted = decrypt(encrypted);
        System.out.println("Decrypted: " + decrypted);
    }

    public static String encrypt(String input) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey keySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptResult =  cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));
        return parseByte2HexStr(encryptResult);
    }

    public static String decrypt(String encryptResultStr) throws GeneralSecurityException {
        byte[] input = parseHexStr2Byte(encryptResultStr);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey keySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        assert input != null;
        return new String(cipher.doFinal(input), StandardCharsets.UTF_8);
    }

    public static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}